package com.lagou.handler;

import com.lagou.request.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {

    // 当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 注意: 客户端将来发送请求的时候会传递一个参数: UserService#sayHello#are you ok
        // 1.判断当前的请求是否符合规则
        System.out.println("");
        RpcRequest rpcRequest = (RpcRequest) msg;
        String className = rpcRequest.getClassName();
        if (!className.contains("UserService")) {
            return;
        }
        Object instance = applicationContext.getBean(className);
        Method method = instance.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        method.setAccessible(true);
        Object result = method.invoke(instance, rpcRequest.getParameters());
        ctx.writeAndFlush(result);
    }

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        UserServiceHandler.applicationContext = applicationContext;
    }
}
